<script setup lang="ts">
import type { CSSProperties } from "vue";
import { reactive, ref, watch } from "vue";
import { Codemirror } from "vue-codemirror";
import { vue } from "@codemirror/lang-vue";
import { oneDark } from "@codemirror/theme-one-dark";
import { Modal, message } from "ant-design-vue";
import { useClipboard } from "@vueuse/core";
const { copy, copied, isSupported } = useClipboard();

// 定义状态
const state = reactive({
  visible: false,
  title: "",
  code: "",
});
interface Props {
  codeStyle?: CSSProperties; // 代码样式
  dark?: boolean; // 是否暗黑主题
  code?: string; // 代码字符串
  // placeholder?: string // 占位文本
  // autofocus?: boolean // 自动聚焦
  // disabled?: boolean // 禁用输入行为和更改状态
  // indentWithTab?: boolean // 启用tab按键
  // tabSize?: number // tab按键缩进空格数
}
const props = withDefaults(defineProps<Props>(), {
  placeholder: "Code goes here...",
  codeStyle: () => {
    return {};
  },
  dark: true,
  code: "",
  autofocus: false,
  disabled: false,
  indentWithTab: true,
  tabSize: 2,
});
const extensions = props.dark ? [vue(), oneDark] : [vue()];
const emits = defineEmits(["update:code", "ready", "change", "focus", "blur"]);
function handleReady(payload: any) {
  // console.log('ready')
  emits("ready", payload);
}
function onChange(value: string, viewUpdate: any) {
  console.log('value',value,viewUpdate)
  emits("change", value, viewUpdate);
  emits("update:code", value);
}
function onFocus(viewUpdate: any) {
  emits("focus", viewUpdate);
}
function onBlur(viewUpdate: any) {
  emits("blur", viewUpdate);
}
const open = (title: any, row: any) => {
  state.title = title;
  state.visible = true;
  state.code = row
};
const cmOptions = ref({
  tabSize: 4,
  theme: "dracula",
  lineNumbers: true,
  lineWrapping: true,
  styleActiveLine: true,
  matchBrackets: true,
  mode: "vue",
  readOnly: true,
});
const onCopy = () => {
  copy(state.code);
};
// 导出给父组件调用
defineExpose({
  open,
});

watch(copied, () => {
  if (copied.value) message.success("复制成功");
});
</script>

<template>
  <Modal
    v-model:open="state.visible"
    :title="state.title"
    @ok="onCopy"
    okText="一键复制"
    width="1000px"
    destroyOnClose
  > 
    <div class="h-130">
      <Codemirror
        style="height: 100%;"
        :disabled="true"
        v-model="state.code"
        :style="codeStyle"
        :options="cmOptions"
        :extensions="extensions"
        v-bind="$attrs"
        :lang="vue()"
        @ready="handleReady"
        @change="onChange"
        @focus="onFocus"
        @blur="onBlur"
      />
    </div>
  </Modal>
</template>

<style lang="less" scoped>
/deep/ .cm-editor {
  border-radius: 8px;
  outline: none;
  border: 1px solid transparent;

  .cm-scroller {
    border-radius: 8px;
  }
}

/deep/ .cm-focused {
  border: 1px solid fade(#000, 48%);
}
</style>
